// subPages/health/connection/connection.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // weightTip: {
    //   tip:''
    // },
    cBtnTxt: {
      cBtnTxt:'重新连接'
    },
    bmiTip: {
      type:''
    },
    bodyFatTip: {
      type:''
    },
    muscleMassTip: {
      type:''
    },
    tip: "请打开蓝牙，保持网络畅通，光脚站在称上",
    mainTip: "",
    serviceId : '',
    deviceId:'',
    characteristicId:'',
    isAgain:false,
    isComplete:false,
    scanTimer : null,
    data16:'',
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // let data = JSON.parse(options.weightTip)
    // var weightTip = 'weightTip.tip';
    if(options.weight && options.weight!='undefined'){
      console.log(options.weight)
      this.setData({
        weightNum: options.weight,
        // [weightTip]: data.tip
      })
    }else{
      this.setData({
        weightNum: 0,
        // [weightTip]: '无数据'
      })
    }
    if(!wx.openBluetoothAdapter){
      this.showError("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
      return;
    }
    this.startConnect();
  },

  startConnect:function(){
    var that = this;
    // 如果适配器已经初始化不在调用初始化(重复初始化会报错)
    // if (that.data.adapterHasInit == undefined || that.data.adapterHasInit) {
    //   wx.showToast({
    //     title: '蓝牙初始化成功',
    //     icon: 'success',
    //   })
    //   setTimeout(function () {
    //     wx.hideToast()
    //   }, 2000)
    //   return;
    // }
    //开启蓝牙适配器
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log("初始化蓝牙适配器" ,res);
        that.getBluetoothAdapterState();
        that.setData({
          isAgain : false,
          mainTip : '蓝牙准备就绪'
        })
      },
      fail: function (err) {
        console.log(err);
        wx.showToast({
          title: '蓝牙初始化失败',
          icon: 'success',
        })
        setTimeout(function () {
          wx.hideToast()
          that.CloseBluetoothAdapter();
          that.stopBluetoothDevicesDiscovery();
          that.setData({
            isAgain : true,
            mainTip : '蓝牙初始化失败,请重新连接'
          })
        }, 2000)
      }
    });
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log("蓝牙2",res)
    })
  },

  //获取本机蓝牙状态
  getBluetoothAdapterState: function () {
    var that = this;
    wx.getBluetoothAdapterState({
      success: function (res) {
        var available = res.available; //判断用户是否开启蓝牙
        var discovering = res.discovering;
        console.log("蓝牙3",res)
        if (!available) {
          wx.showToast({
            title: '请开蓝牙',
            icon: 'loading',
          })
          setTimeout(function () {
            wx.hideToast();
          }, 2000)
        }
        else {
          if (!discovering) {
            that.startBluetoothDevicesDiscovery();//开始扫描附近的蓝牙设备
          }
        }
      }
    })
  },

  // 开始搜索新设备
  startBluetoothDevicesDiscovery: function () {
    var that = this;
    that.setData({
      isAgain : false,
      mainTip : '正在搜索...'
    })
    wx.startBluetoothDevicesDiscovery({
      services: [],
      allowDuplicatesKey: false,
      success: function (res) {
        console.log("蓝牙4",res)
        if (!res.isDiscovering) {
          that.getBluetoothAdapterState();
        }
        else {
          that.onBluetoothDeviceFound();//监听寻找到新设备的事件
        }
      },
      fail: function (err) {
        console.log(err);
        setTimeout(function () {
          that.setData({
            isAgain : true,
            mainTip : '蓝牙搜索失败,请重新连接'
          })
          that.CloseBluetoothAdapter();
          that.stopBluetoothDevicesDiscovery();
        }, 2000)
      }
    });
    if (that.scanTimer != null) {
      clearTimeout(that.scanTimer)
    }
    that.scanTimer = setTimeout(() => {
      // 一直没有搜到设备
      that.setData({
        isAgain : true,
        mainTip : '蓝牙搜索超时,请重新连接'
      })
      that.CloseBluetoothAdapter();
      that.stopBluetoothDevicesDiscovery();
    }, 30000)
  },

  // 监听寻找到新设备的事件
  onBluetoothDeviceFound: function () {
    var that = this;
    wx.onBluetoothDeviceFound(function (res) {
      console.log("蓝牙5",res)
      if (res.devices[0]) {
        var name = res.devices[0]['name'];
        var localName = res.devices[0]['localName'];
        if (name != '') {
          if (name.indexOf('Health Scale') != -1 || name.indexOf('LFScale') != -1) {
            var deviceId = res.devices[0]['deviceId'];
            that.deviceId = deviceId;
            // console.log(that.deviceId);
            that.setData({
              mainTip : '正在连接...'
            })
            that.startConnectDevices();
          }
        }
        else if (localName != '' && localName != undefined) {
          if (localName.indexOf('Health Scale') != -1 || localName.indexOf('LFScale') != -1) {
            var deviceId = res.devices[0]['deviceId'];
            that.deviceId = deviceId;
            // console.log(that.deviceId);
            that.setData({
              mainTip : '正在连接...'
            })
            that.startConnectDevices();
          }
        }
      }
    })
  },
  
  // 自动连接设备
  startConnectDevices: function () {
    var that = this;
    wx.createBLEConnection({
      deviceId: that.deviceId,
      success: function (res) {
        console.log("蓝牙6",res)
        if (res.errCode == 0) {
          setTimeout(function () {
            that.setData({
              mainTip : '已连接'
            })
            that.getService(that.deviceId);
          }, 3000)
        }
      },
      fail: function (err) {
        console.log('连接失败：', err);
        setTimeout(function () {
          that.setData({
            isAgain: true,
            mainTip : '蓝牙连接失败,请重新连接'
          })
          that.CloseBluetoothAdapter();
          that.stopBluetoothDevicesDiscovery();
          that.closeBLEConnection();
        }, 2000)
      },
    });
  },

  //关闭蓝牙适配器
  CloseBluetoothAdapter:function(){
    wx.closeBluetoothAdapter ({
      success:function(res){
        console.log('关闭蓝牙适配器',res)
      }
    })
  },

  //关闭蓝牙搜索
  stopBluetoothDevicesDiscovery:function(){
    var that = this
    if (that.scanTimer!=null) {
      clearTimeout(that.scanTimer)
      that.scanTimer = null
    }
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log('蓝牙连接',res)
        wx.hideLoading ()
      }
    })
  },

  //关闭蓝牙连接
  closeBLEConnection:function(){
    var that = this
    wx.closeBLEConnection({
      deviceId: that.deviceId,
      success: function (res) {
        console.log('蓝牙连接',res)
        // that.setData({
        //   isAgain : true,
        // })
      }
    })
  },
  
  // 连接成功后握手
  getService: function (deviceId) {
    var that = this;
    that.stopBluetoothDevicesDiscovery();
    // 监听蓝牙连接
    wx.onBLEConnectionStateChange(function (res) {
      console.log('蓝牙7',res);
      // if(!res.connected){
      //   that.setData({
      //     mainTip : '断开连接'
      //   })
      //   that.closeBLEConnection();
      // }
    });
    // 获取蓝牙设备service值
    wx.getBLEDeviceServices({
      deviceId,
      success: function (res) {
        console.log('蓝牙8',res);
        that.setData({
          mainTip : '正在传输数据...'
        })
        var deviceService = res.services
        for (var i = 0; i < deviceService.length; i++) {
          var serviceId = deviceService[i].uuid.substring(4, 8)
          if (serviceId === 'FFF0') {                  //‘FFF0’为设备定义的读写UUID
            that.serviceId = deviceService[i].uuid
          }
        }
        that.getCharacter(deviceId, that.serviceId);
      }
    })
  },

  // 读取服务的特征值
  getCharacter: function (deviceId,serviceId) {
    var that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function (res) {
        console.log('蓝牙发送',res)
        // console.log(res.characteristics)
        for (var i = 0; i < res.characteristics.length; i++) {
          var item = res.characteristics[i];
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              success: function (res) {
                console.log('读取数据', res);
              }
            })
          }
          if (item.properties.write) {
            that.characteristicId = item.uuid
            that.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
              success: function (res) {
                console.log('通信', res);
              }
            })
          }
        }
      },
      fail: function (err) {
        console.log('getBLEDeviceCharacteristics',err);
        that.setData({
          isAgain: true,
          mainTip : '传输数据失败,请重新连接'
        })
        that.CloseBluetoothAdapter();
        that.closeBLEConnection();
      }
    })

    //通信监听 用于接收数据
    wx.onBLECharacteristicValueChange(function (characteristic) {
      var result = that.buf2hex(characteristic.value);
      console.log('蓝牙通信 接受到的数据',result);
      if(result.length > 4)
      {
        if(result.substring(0, 2) == "cf"){
          that.setData({
            mainTip : '成功传输数据',
            data16 : result
          })
          that.dataProcessing();
        }
        else
        {
          that.setData({
            isAgain : true,
            mainTip : '无法识别的蓝牙设备,请重新连接'
          })
          that.CloseBluetoothAdapter();
          that.closeBLEConnection();
          return;
        }
      }
    })
  },

  //写入数据
  writeBLECharacteristicValue() {
    var that = this;
    var data = 'FD370001000000000000CB'
    var buffer = that.stringToHexBuffer(data)
    // console.log(buffer);
    wx.writeBLECharacteristicValue({
      deviceId: that.deviceId,
      serviceId: that.serviceId,
      characteristicId: that.characteristicId,
      value: buffer,
    })
  },

  //数据处理
  dataProcessing:function(){
    var that = this
    // console.log(that.data.data16)
    var weight = that.CalculateWeight(that.data.data16);//体重
    var impedance = that.EncryptionImpedance(that.data.data16);//加密抗组
    console.log(weight);
    console.log(impedance);
    console.log(app.globalData.userId);
    if(weight != 0 && impedance != -1)
    {
      wx.request({
        url: app.globalData.apiUrl +'/checkadd',
        data: {
          userid: app.globalData.userId,
          weight: weight,
          resistance: impedance
        },
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded' //默认值
        },
        success: function (res) {
          console.log(res);
          if(res.statusCode == '200')
          {
            if(res.data.code == '200')
            {
              var weightTip = 'weightTip.tip';
              var bmiType = 'bmiTip.type';
              var bodyFatType = 'bodyFatTip.type';
              var muscleMassType = 'muscleMassTip.type';
              that.setData({
                mainTip : '传输数据完成',
                [weightTip]: res.data.data.v1,
                isComplete: true,
                analysisBtn: true,
                isShow: true,
                bmi: res.data.data.v6,
                [bmiType]:res.data.data.v7,
                bodyFat: res.data.data.v2,
                [bodyFatType]: res.data.data.v3,
                muscleMass: res.data.data.v4,
                [muscleMassType]: res.data.data.v5,
                id: res.data.data.id
              })
              that.CloseBluetoothAdapter();
              that.closeBLEConnection();
            }else if(res.data.code == '300'){
              var weightTip = 'weightTip.tip';
              that.setData({
                [weightTip]: res.data.data,
                isComplete: true,
                isShow: false,
                analysisBtn: false
              })
            }
          }else{
            that.setData({
              isAgain : true,
              mainTip : '传输数据失败,请重新连接'
            })
            that.CloseBluetoothAdapter();
            that.closeBLEConnection();
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
      })
    }
    else
    {
      that.setData({
        isAgain : true,
        mainTip : '传输数据失败,请重新连接'
      })
      that.CloseBluetoothAdapter();
      that.closeBLEConnection();
    }
  },

  //加密阻抗转换
  EncryptionImpedance:function(data16){
    var impedance16 = data16.substring(10, 16);
    if(impedance16.length == 6){
      var impedanceA = impedance16.substring(0,2);
      var impedanceB = impedance16.substring(2,4);
      var impedanceC = impedance16.substring(4,6);
      var impedance = impedanceC + impedanceB + impedanceA
      return parseInt(impedance,16)
    }
    return -1
  },

  //计算体重
  CalculateWeight:function(data16){
    var weight16 = data16.substring(6, 10);
    if(weight16.length == 4)
    {
      var weightA = weight16.substring(0,2);
      var weightB = weight16.substring(2,4);
      weight16 = weightB + weightA;
      var weight =  this.accMul(parseInt(weight16,16),0.01)
      this.setData({
        weightNum:weight
      })
      return weight;
    }
    return 0
  },

  //js 两个整数相乘
  accMul:function(arg1,arg2)
  {
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try
    {
      m+=s1.split(".")[1].length
        
    }
    catch(e)
    {}
    try
    {
      m+=s2.split(".")[1].length
    }
    catch(e)
    {}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
  },
  
  // 接收到通知数据 ArrayBuffer解析出16进制
  buf2hex: function (buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  },
  
  //16进制转换ArrayBuffer
  stringToHexBuffer: function (data) {
    var typedArray = new Uint8Array(data.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
    }))
    return typedArray.buffer
  },

  // 重新连接
  connection:function(){
    this.startConnect();
  },

  connection2:function(){
    var that = this 
    that.setData({
      isAgain:false,
      isComplete:false,
    })
    this.startConnect();
  },

  analysis:function(){
    var that= this
    // console.log(that.data.id);
    wx.navigateTo({
      url: '../analysis/analysis?id='+ that.data.id,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      isAgain : false,
      mainTip : '',
      isComplete:false,
    })
    this.CloseBluetoothAdapter();
    this.stopBluetoothDevicesDiscovery();
    this.closeBLEConnection();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      isAgain : false,
      mainTip : '',
      isComplete:false,
    })
    this.CloseBluetoothAdapter();
    this.stopBluetoothDevicesDiscovery();
    this.closeBLEConnection();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN小程序',
      path: 'pages/index/index?puid=' + app.globalData.userId,
      success: function(res) {
          res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})